<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>轮播图页面搭建(Building a carousel page)</title>
  <link rel="stylesheet" href="./css/reset.css">
  <link rel="stylesheet" href="./css/common.css">
  <style>
    .banner {
      width: 1920px;
      height: 550px;
    }
    
    .banner .images {
      position: relative;
    }

    .banner .images .item {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      overflow: hidden;

      opacity: 0;
    }

    .banner .images .item.active {
      opacity: 1;
    }

    .banner .images .item img {
      position: relative;
      transform: translate(-50%);
      left: 50%;
      width: 1920px;
      height: 550px;
    }
    
  </style>
</head>
<body>

  <div class="banner">
    <ul class="images"></ul>
    <div class="indicator"></div>
  </div>
  <div class="control">
    <button onclick="prev()">上一个</button>
    <button onclick="next()">下一个</button>
  </div>

  <script src="./json/banner_data.js"></script>
  <script>
    const bannerServerUrl = "https://res.vmallres.com/"

    const imagesEl = document.querySelector(".images")
    const activeItemEl = null

    banners.forEach(item => {
      const liEl = document.createElement("li")
      liEl.classList.add("item")
      const imgEl = document.createElement("img")
      imgEl.src = bannerServerUrl + item.imgUrl;
      liEl.appendChild(imgEl)
      imagesEl.appendChild(liEl)
    })

    imagesEl.children[0].classList.add("active")

    let activeEl = document.querySelector(".images .item.active")
    let currentIndex = 0
    function next() {
      currentIndex++
      switchImage()
    }

    function prev() {
      currentIndex--
      switchImage()
    }
    
    function switchImage() {
      if (currentIndex >= imagesEl.children.length) {
        currentIndex = 0
      }
      if (currentIndex < 0) {
        currentIndex = imagesEl.children.length - 1
      }
      
      activeEl.classList.remove("active")
      const newActiveEl = imagesEl.children[currentIndex]
      newActiveEl.style.transition = "opacity .8s ease"

      newActiveEl.classList.add("active")
      activeEl = newActiveEl
    }

    
  </script>
  
</body>
</html>